package org.zhc.filter;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.zhc.context.ActionContext;
import org.zhc.po.HttpContext;
import org.zhc.service.ActionInvokeHandler;
import org.zhc.service.LoadConfigService;
import org.zhc.service.impl.ActionInvokeHandlerImpl;
import org.zhc.service.impl.LoadAnnotationConfig;
import org.zhc.service.impl.LoadXMLConfig;


public class ActionFilter implements Filter {

	private static final Logger logger = Logger.getLogger(ActionFilter.class
			.getName());

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse rep,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) rep;
		String url = request.getServletPath();
		int split = url.lastIndexOf("/");
		String namespace = url.substring(0, split);
		namespace = namespace.isEmpty() ? "/" : namespace;
		String actionName = url.substring(split + 1);
		int lastPoint = actionName.lastIndexOf(".");
		actionName = actionName.substring(0, lastPoint);
		long begin = System.currentTimeMillis();
		ActionInvokeHandler handler = new ActionInvokeHandlerImpl(
				new HttpContext(request, response), namespace, actionName);
		handler.invoke(namespace, actionName);
		logger.info("处理请求：" + url + " 耗时："
				+ (System.currentTimeMillis() - begin) + " ms.");
	}

	/**
	 * 
	 * 
	 * @param config
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		logger.info("Begin to load config.");
		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("/struts.xml");
		LoadConfigService loadXML = null;
		ActionContext.initApplicationBasePath(config.getServletContext()
				.getContextPath());
		ActionContext.initApplicationFilePath(config.getServletContext()
				.getRealPath("/"));
		if (inputStream == null) {
			logger.info("No struts.xml found under classpath.trying to resovle annotation");
			loadXML = new LoadAnnotationConfig();
			try {
				loadXML.loadAcionConfig(null);
			} catch (DocumentException e) {
				logger.error(e.getMessage());
			}
		} else {
			logger.info("Begin to load config file.");
			try {
				loadXML = new LoadXMLConfig();
				loadXML.loadAcionConfig(inputStream);
				logger.info("Config file load success.");
			} catch (DocumentException e) {
				logger.info(e.getMessage());
			}
		}
	}
}
